package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    /**
     * 用户登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //检查参数
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断是否是游客
        if (dto.getPassword()==null&&dto.getPhone()==null&&dto.getEquipmentId()!=null){
            ApUser apUser=new ApUser();
            apUser.setId(0);
            apUser.setName("游客");
            apUser.setPhone(dto.getEquipmentId().toString());
            String token = AppJwtUtil.getToken(apUser);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //查询数据库
        ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
        if (apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //比对密码
        String pswd = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
        if (pswd.equals(apUser.getPassword())){

            Map<String, Object> map = Maps.newHashMap();
            String token = AppJwtUtil.getToken(apUser);

            apUser.setPassword(""); //返回前台是不显示密码   保护用户信息
            apUser.setSalt("");     //返回前台不显示盐      保护用户信息

            map.put("token",token);
            map.put("User",apUser);

            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //返回结果
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户或密码错误");
    }
}
